<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use App\Comment;
use App\Zan;

class PostController extends Controller
{
    //首页
    public function index()
    {
        $posts = Post::orderBy('created_at', 'desc')->withCount(["zans", "comment"])->with(['user'])->paginate(3);
        return view('post/index',compact('posts'));
    }
    //文章详情页面
    public function show(Post $post)
    {
        return view('post/show',compact('post'));
    }
    //创建文章
    public function create()
    {
        return view('post/create');
    }
    //创建文章逻辑
    public function store()
    {
        //验证
        $this->validate(request(), [
            'title' => 'required|unique:posts|max:30',
            'content' => 'required',
        ]);
        $user_id = \Auth::id();
        $params = array_merge(request(['title','content']),compact('user_id'));
        Post::create($params);
        return redirect('/posts');
    }
    //编辑页面
    public function edit(Post $post)
    {
        return view('post/edit',compact('post'));
    }
    //编辑页面逻辑
    public function update(Post $post)
    {
        //验证
        $this->validate(request(), [
            'title' => 'unique:posts|max:100',
            'content' => '  ',
        ]);
        $this->authorize('update',$post);
        //逻辑
        $post->title = request("title");
        $post->content = request("content");
        $post->save();
        //渲染
        return redirect("/posts/{$post->id}");
    }
    //删除页面
    public function delete(Post $post)
    {
        //用户验证
        $this->authorize('delete',$post);
        //删除
        $post->delete();
        //页面渲染
        return redirect('/posts');
    }
    //上传图片
    public function imageUpload(Request $request)
    {
        $path = $request->file('wangEditorH5File')->storePublicly(md5(time()));
        return asset('storage/'.$path);
    }
    //提交评论
    public function comment(Post $post)
    {
        $this->validate(request(),[
            'content'=>'required',
        ]);
        $comment = new Comment();
        $comment->user_id = \Auth::id();
        $comment->content = request('content');
        $post->comment()->save($comment);
        return back();
    }

    public function zan(Post $post)
    {
        $zan = new \App\Zan;
        $zan->user_id = \Auth::id();
        $post->zans()->save($zan);
        return back();
    }

    /*
     * 取消点赞
     */
    public function unzan(Post $post)
    {
        $post->zan(\Auth::id())->delete();
        return back();
    }
    public function hot()
    {
        $posts = Post::orderBy('comment_count', 'desc')->withCount(["zans", "comment"])->with(['user'])->paginate(3);
        return view('hot/hot',compact('posts'));
    }

}
